package ar.edu.unlam.tpfinal.struts.actions.client;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import ar.edu.unlam.tpfinal.service.ClientService;
import ar.edu.unlam.tpfinal.service.exceptions.ServiceException;
import ar.edu.unlam.tpfinal.struts.exceptions.PresentationException;
import ar.edu.unlam.tpfinal.struts.forms.AddressForm;
import ar.edu.unlam.tpfinal.struts.forms.ClientAddressForm;
import ar.edu.unlam.tpfinal.struts.forms.ClientForm;

public class ViewClientAction extends BaseClientAction {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
							  	 HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		logger.debug("Inside ViewClientAction");
		
		logger.debug("Getting ALL clients");
		
		// Obtener servicio del contexto mediante Spring
		logger.debug("Getting service from context");
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
		ClientService clientService = (ClientService) context.getBean("clientService");
		
		List<ClientAddressForm> clientAddressList = new ArrayList<ClientAddressForm>();
		
		try {
			// Mediante el servicio obtenemos TODOS los clientes
			List<ClientForm> clientList = clientService.getAllClients();
			
			for(ClientForm clientForm : clientList) {
				ClientAddressForm clientAddressForm = new ClientAddressForm();
				clientAddressForm.setClient(clientForm);
				
				// De cada cliente agregamos las direcciones
				List<AddressForm> addressForm = clientService.getAllAddressesFromClient(clientForm.getOid());
				clientAddressForm.setAddressList(addressForm);

				// Agregamos cada cliente al formulario
				clientAddressList.add(clientAddressForm);
			}
		
			// Las colocamos en el request
			request.setAttribute("clientAddressList", clientAddressList);
			
			// Volvemos
			return mapping.findForward("success");
		} catch(ServiceException ex) {
			throw new PresentationException(ex);
		}

	}
	
}